package com.handu.luna.core.domain.promotion;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.persistence.*;
import javax.persistence.criteria.*;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Size;

import com.handu.luna.core.domain.BasePersistentDomain;
import com.handu.luna.core.domain.advertisement.AdvertiseList;
import com.handu.luna.core.domain.goods.Goods;
import com.handu.luna.core.domain.search.TopicSearch;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.format.annotation.DateTimeFormat;

@Entity
public class Topic extends BasePersistentDomain<TopicRepository>{

    @Transient private String status;

    public enum PromotionStatus{
		UNACTIVATED("即将开始"),ACTIVATING("正在进行"),ACTIVATED("已过期");
        public String description;
        PromotionStatus(final String description) {
         this.description = description;
        }
	}

    public static final String DELIMITER = ",";

    //专题名称
 	@Size(min=1,max=100, message="专题名称长度不能为空或超过100字。")
	private String name;
    //文件名称
    private String fileName;
    //url地址
    private String url;
    //开始时间
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date startDate;
	//结束时间
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date endDate;
    //图片
    private String imgFile;
    //排序
    @Min(value = 0,message = "不能小于0")
	@Max(value=254,message="最大不能超过255")
    private int displayOrder = 100;
    //seo-关键字
    private String keywords;
    //seo-描述
    private String description;
    //模板文件
    private String templateFile;

    //专题内容
    @Lob
    private String content;

    private String topicModules;
    @Transient private int step = 1;
    @Transient private List<TopicModule> topicModuleList;
    @Transient private List<Long> topicModuleIdList;
    @Transient private List<Long> deleteIdList;

    public String getStatus() {
        return initStatus(this.getStartDate(),this.getEndDate());
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String initStatus(Date startDate,Date endDate) {

        Date now = new Date();
		if(now.compareTo(startDate)==-1){
			status =  "<font color='#006400'> 【"+PromotionStatus.UNACTIVATED.description+"】</font>";
		}else if(endDate.compareTo(now)==-1){
			status = "<font color='#696969'>【"+PromotionStatus.ACTIVATED.description+"】</font>";
		}else{
			status = "<font color='#8B0000'>【"+PromotionStatus.ACTIVATING.description+"】</font>";
		}

        return status;
    }

    public static Specification<Topic> selectCondition(TopicSearch topicSearch) {
		return new Specification<Topic>() {
			@Override
			public Predicate toPredicate(Root<Topic> root,
					CriteriaQuery<?> query, CriteriaBuilder builder) {

				Predicate predicate = builder.conjunction();
				List<Expression<Boolean>> expressions = predicate.getExpressions();

				if (StringUtils.isNotBlank(topicSearch.getName())) {
					expressions.add(builder.like(root.<String> get("name"),"%"+topicSearch.getName() +"%"));
				}

				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date date1 = null;
				Date date2 = null;

				if(StringUtils.isNotBlank(topicSearch.getStartDate())){
					try {
						date1 = sdf.parse(topicSearch.getStartDate());
					} catch (ParseException e) {
						e.printStackTrace();
					}
					expressions.add(builder.greaterThanOrEqualTo(root.<Date>get("startDate"), date1));
				}

				if(StringUtils.isNotBlank(topicSearch.getEndDate())){
					try {
						date2 = sdf.parse(topicSearch.getEndDate());
					} catch (ParseException e) {
						e.printStackTrace();
					}
					expressions.add(builder.lessThanOrEqualTo(root.<Date>get("startDate"), date2));
				}

                if(StringUtils.isNotBlank(topicSearch.getStatus())) {
                   if(topicSearch.getStatus().equals(Promotion.PromotionStatus.UNACTIVATED.description)) {
                       expressions.add(builder.greaterThan(root.<Date>get("startDate"), new Date()));
                   }else if(topicSearch.getStatus().equals(Promotion.PromotionStatus.ACTIVATING.description)) {
                       expressions.add(builder.lessThan(root.<Date>get("startDate"), new Date()));
                       expressions.add(builder.greaterThan(root.<Date>get("endDate"), new Date()));
                   }else if(topicSearch.getStatus().equals(Promotion.PromotionStatus.ACTIVATED.description)){
                       expressions.add(builder.lessThan(root.<Date>get("endDate"), new Date()));
                   }
                }

				return query.where(predicate).getRestriction();

			}
		};
	}

    @PostLoad
    public void init() {
        if(StringUtils.isNotBlank(topicModules)) {
            topicModuleList = new ArrayList<>();
            for (String moduleStrId : this.strToList(topicModules)) {
                long moduleId = Long.parseLong(moduleStrId);
                topicModuleList.add(context.getTopicModuleRepository().findOne(moduleId));
            }
        }
    }

    @PrePersist
    public void prePersist() {
        if(CollectionUtils.isNotEmpty(topicModuleList)) {
            topicModuleIdList = new ArrayList<>();
            for(TopicModule topicModule : topicModuleList) {
                if(topicModule.isNew()) {
                    topicModule = context.getTopicModuleRepository().save(topicModule);
                }else {
                    topicModule = topicModule.update();
                }

                topicModuleIdList.add(topicModule.getId());
            }

            topicModules = this.listToStr(topicModuleIdList);
        }else {
            topicModules = "";
        }
    }


    //模块添加与修改
    public void updateTopicModules() {

        topicModuleIdList = new ArrayList<>();

        if(CollectionUtils.isNotEmpty(getTopicModuleList())) {
            for(TopicModule topicModule :getTopicModuleList()) {
                if(topicModule.isNew()) {
                    TopicModule newTopicModule = context.getTopicModuleRepository().save(topicModule);
                    topicModuleIdList.add(newTopicModule.getId());
                }else {
                    context.getTopicModuleRepository().update(topicModule.getName(),topicModule.getGoodsNum(),topicModule.getDisplayOrder(),topicModule.getAdPositionId(),topicModule.getId());
                    topicModuleIdList.add(topicModule.getId());
                }
            }
        }

        topicModules = this.listToStr(topicModuleIdList);
        context.getTopicRepository().updateTopicModules(topicModules,this.getId());
    }

    //商品添加与修改
    public void updateGoods() {

        Topic topic = context.getTopicRepository().findOne(this.getId());
        List<TopicModule> moduleList = new ArrayList<>();
        int moduleNum = 0;
        if(null != topic.getTopicModuleList()) {
            moduleList = topic.getTopicModuleList();
            moduleNum = topic.getTopicModuleList().size();
        }

        List<List<Long>> allGoodsList = new ArrayList<>();
        int goodsColNum = 0;
        if(this.getTopicModuleList() != null) {
           goodsColNum = this.getTopicModuleList().size();
        }

        for(int i=0; i<goodsColNum; i++) {
            allGoodsList.add(this.getTopicModuleList().get(i).getGoodsIdList());
        }

        for(int i=0; i<moduleNum - goodsColNum; i++) {
            allGoodsList.add(new ArrayList<>());
        }

        for(int i=0; i<moduleList.size(); i++) {
            TopicModule topicModule = moduleList.get(i);
            context.getTopicModuleRepository().updateGoods(this.listToStr(allGoodsList.get(i)),topicModule.getId());
        }




    }

    public Topic update() {
        prePersist();
        return context.getTopicRepository().save(this);
    }

    public String listToStr(List<Long> list) {
        StringBuilder sb = new StringBuilder();
        for (Long id : list) {
            sb.append(String.valueOf(id)).append(DELIMITER);
        }
        return sb.toString();
    }

    public List<String> strToList(String arrayString) {
        List<String> list = new ArrayList<String>();
        for(String item : arrayString.split(DELIMITER)) {
            list.add(item);
        }
        return list;
    }


	public Topic(){}

    public Topic(String name,String fileName, Date startDate, Date endDate) {
        this.name = name;
        this.fileName = fileName;
        this.startDate = startDate;
        this.endDate = endDate;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public String getImgFile() {
        return imgFile;
    }

    public void setImgFile(String imgFile) {
        this.imgFile = imgFile;
    }

    public int getDisplayOrder() {
        return displayOrder;
    }

    public void setDisplayOrder(int displayOrder) {
        this.displayOrder = displayOrder;
    }

    public String getKeywords() {
        return keywords;
    }

    public void setKeywords(String keywords) {
        this.keywords = keywords;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getTemplateFile() {
        return templateFile;
    }

    public void setTemplateFile(String templateFile) {
        this.templateFile = templateFile;
    }

    public String getTopicModules() {
        return topicModules;
    }

    public void setTopicModules(String topicModules) {
        this.topicModules = topicModules;
    }

    public List<TopicModule> getTopicModuleList() {
        return topicModuleList;
    }

    public void setTopicModuleList(List<TopicModule> topicModuleList) {
        this.topicModuleList = topicModuleList;
    }

    public List<Long> getTopicModuleIdList() {
        return topicModuleIdList;
    }

    public void setTopicModuleIdList(List<Long> topicModuleIdList) {
        this.topicModuleIdList = topicModuleIdList;
    }

    public int getStep() {
        return step;
    }

    public void setStep(int step) {
        this.step = step;
    }

    public List<Long> getDeleteIdList() {
        return deleteIdList;
    }

    public void setDeleteIdList(List<Long> deleteIdList) {
        this.deleteIdList = deleteIdList;
    }

    /**
     * 首页  获得专题里面模块所添加的商品信息   lxx
     */
    
/*    public List<Goods> getTopicGoodsInfo(long topicId){
    	Topic topicGoods = context.getTopicRepository().findByTopicId(topicId);   //Long.parseLong("1")
    	List<Goods> goodsList = new ArrayList<>();
        String[] strArr = topicGoods.getTopicModules().split(",");
    	if(StringUtils.isNotBlank(topicGoods.getTopicModules())){
    		for(String moduleId : strArr){
    			 goodsList = topicGoods.getTopicModuleList().get(Integer.parseInt(moduleId)).getGoodsList();
    		}
    		 //goodsList = topicGoods.getTopicModuleList().get(0).getGoodsList();
    	}               
        return 	goodsList;      
    }*/       
    
    public HashMap<String,List<Goods>>  getTopicGoodsInfo(long topicId){
    	Topic topicGoods = context.getTopicRepository().findByTopicId(topicId);   //Long.parseLong("1")    
    	HashMap<String, List<Goods>> map = new HashMap<String , List<Goods>>(); 
    	Goods goodsMethod = new Goods();
    if(topicGoods!=null){
    	if(StringUtils.isNotBlank(topicGoods.getTopicModules())){
    		String[] strArr = topicGoods.getTopicModules().split(",");
    		for(int i=0; i<strArr.length; i++) {               
    			 String moduleName = topicGoods.getTopicModuleList().get(i).getName();
    			 List<Goods> goodsList = topicGoods.getTopicModuleList().get(i).getGoodsList();
    			 List<Goods> endGoodsList = new ArrayList<Goods>();
    			 int j = 0;
    			 for(Goods goods : goodsList){
    			   if(j < topicGoods.getTopicModuleList().get(i).getGoodsNum()){
    				  if(goods.getGoodsStore() >= goods.getReservedStore()){  //当库存大于等于库存预留量的时候
    					  endGoodsList.add(goods);		
    				      j++; 
    				  } 
    			   }else{
    				   break;
    			   }
    			 }
    			
    			 goodsMethod.handleGoodsPrice(endGoodsList);   			
    			 map.put(moduleName, endGoodsList);//topicGoods.getTopicModuleList().get(i).getGoodsList()    			
    		}
    	} 
    }
        return map;      
     }
    
    /**
     *-----------------------------------------
     *  @Function
     *  @Params 处理 专题模块
     *  @return List<TopicModule> 
     *  @author 邹永禹 Luna项目组
     *  @date  2014年9月26日 上午9:18:38
     *-----------------------------------------
     */
    public List<TopicModule> handleTopicModule(List<TopicModule> topicModule){

		//-------------对专题模块进行排序、对专题模块下的商品进行排序----------------------------------
		//	1 去掉广告位和商品同时为空的专题模块
		//	2 对专题模块进行排序 条件TopicModule.displayOrder
		//	3 对专题模块下的广告位和商品进行处理
		//	  3.1将广告位下的广告添加进去
		//	  3.2根据专题模块设置的商品数去掉多余的商品TopicModule.goodsNum
    	if(topicModule != null && topicModule.size() > 0)
    	{
    		List<TopicModule> orderModuleAndGoods = topicModule;
    		//-----------去掉 广告位和商品同时为空的专题模块--------------------------------------------------------
			List<TopicModule> delTopicModules = new ArrayList<TopicModule>(orderModuleAndGoods.size());
			for(int i = 0;i < orderModuleAndGoods.size();i++){
				TopicModule delTopicModule = orderModuleAndGoods.get(i);
				//广告位 和 商品同时为空
				if(delTopicModule.getAdPositionId() == 0 && (delTopicModule.getGoodsList()==null)){
					delTopicModules.add(delTopicModule);
				}
			}
			orderModuleAndGoods.removeAll(delTopicModules);
			//----------去掉 广告位和商品同时为空的专题模块End------------------------------------------------------
			
			//------------专题模块排序  条件TopicModule.displayOrder----------------
			Collections.sort(orderModuleAndGoods,new Comparator<TopicModule>(){
				public int compare(TopicModule tm1, TopicModule tm2) {
					if (tm1.getDisplayOrder() > tm2.getDisplayOrder()) {
						return 1;
					} else if (tm1.getDisplayOrder() == tm2.getDisplayOrder()) {
						return 0;
					}
					return -1;
				}
				
			});
		    //---------------专题模块排序End---------------------------------------
			
			//---------------对专题模块下的广告位和商品进行处理---------------------------
			int moduleNumber = orderModuleAndGoods.size();
			
			for (int i = 0; i < moduleNumber; i++) {
			
				TopicModule currentMod = orderModuleAndGoods.get(i);
				
				//-------如果有商品,去掉多余显示数目的商品--------------------
				List<Goods> goodsList = currentMod.getGoodsList();
				if (goodsList != null && (goodsList.size() > 0)) {
					
					//-------------获取促销价格 如果没有促销价格,则使用本店价格shopPrice----------------
					List<Goods> delGoods = new ArrayList<Goods>(goodsList.size());
					for(int j = 0;j < goodsList.size();j++){
						Goods g = goodsList.get(j);
						if(!g.isDisplayed()){
							delGoods.add(g);
						}
						List<SalesPromotion> sp = context.getSalesPromotionGoodsRepository().findCurrentSalesPromotionByGoodsId(g.getId(), new Date());
						if(sp != null && sp.size() > 0){
							SalesPromotionGoods spg = context.getSalesPromotionGoodsRepository().findBySalesPromotionIdAndGoodsId(sp.get(0).getId(), g.getId());
							g.setShowPrice(spg.getGoodsPrice());
						}else{
							g.setShowPrice(g.getShopPrice());
						}
					}
					goodsList.removeAll(delGoods);//去掉下架的商品
					//----获取促销价格 如果没有促销价格,则使用本店价格shopPriceEnd-----------------------------------
					
					//----------排除不再专题模块设置数量内的商品-----------------------------------
					int showGoosNumber = currentMod.getGoodsNum();
					if (goodsList.size() > showGoosNumber) {
						goodsList.removeAll(goodsList.subList(showGoosNumber, goodsList.size()));
					}
					//---------排除多余商品 不再设置数量内的商品End----------------------------------------------
				}
				currentMod.setGoodsList(goodsList);
				//-------如果有商品，去掉多余显示数目的商品End----------------------------------------
				
				
				//-------将相应的广告放到广告位下,如果有广告位的话---------------------------
				long adPositionId = currentMod.getAdPositionId();
				if(adPositionId != 0){
					List<AdvertiseList> advertiseList = context.getAdvertiseListRepository().
							findByAdPositionIdForPortal(adPositionId);
					
					if(advertiseList != null && advertiseList.size()>0){
						
						//对于广告位路径 不以http开头的 添加CONTEXT_PATH
						for(int k=0;k<advertiseList.size();k++){
							String adOldUrl = advertiseList.get(k).getAdvertiseImageUrl();
							if(adOldUrl.indexOf("http")<0){
								advertiseList.get(k).setAdvertiseImageUrl("http://192.168.1.182:8999"+adOldUrl);	
							}
						}
						
						
						currentMod.getAdPosition().setAdvertiseList(advertiseList);
					}
				}
				//-------将相应的广告放到广告位下End--------------------------------------
				orderModuleAndGoods.set(i, currentMod);
			}
			return orderModuleAndGoods;
    	}
    	return null;
    }

}
